package com.zhong.blog.handle;

import com.baomidou.mybatisplus.extension.api.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhong.blog.components.JwtTokenUtil;
import com.zhong.blog.components.TokenCache;
import com.zhong.blog.config.JSONAuthentication;
//import com.zhong.blog.utlis.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    private ObjectMapper objectMapper;
    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        log.info("登录验证成功");
//        response.setContentType("application/json;charset=UTF-8"); // 响应类型
//        response.getWriter().write(objectMapper.writeValueAsString("{code:'200',data:'登录验证成功'}"));

        //取得账号信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //
        System.out.println("userDetails = " + userDetails);
        //取token
        //好的解决方案，登录成功后token存储到数据库中
        //只要token还在过期内，不需要每次重新生成
        //先去缓存中找
        String token = TokenCache.getTokenFromCache(userDetails.getUsername());
        if(token == null) {
            System.out.println("初次登录，token还没有，生成新token。。。。。。");
            //如果token为空，则去创建一个新的token
            token = jwtTokenUtil.generateToken(userDetails);
            //把新的token存储到缓存中
            TokenCache.setToken(userDetails.getUsername(),token);
            System.out.println("存储的键："+userDetails.getUsername());
            System.out.println("存储的token");
            System.out.println(token);
        }else if (jwtTokenUtil.isTokenExpired(token)){
            System.out.println("token已过期。。。。。。");
            //如果token为空，则去创建一个新的token
            token = jwtTokenUtil.generateToken(userDetails);
            //把新的token存储到缓存中
            TokenCache.setToken(userDetails.getUsername(),token);
            System.out.println("存储的键："+userDetails.getUsername());
            System.out.println("存储的token");
            System.out.println(token);
        }


        //
        Map<String,Object> map = new HashMap<>();
        map.put("username",userDetails.getUsername());
        map.put("auth",userDetails.getAuthorities());
        map.put("token",token);
        //装入token
        R<Map<String,Object>> data = R.ok(map);
//        R data = R.ok().put("username", userDetails.getUsername())
//                .put("auth", userDetails.getAuthorities())
//                .put("token", token);
        //输出
        this.WriteJSON(request, response, data);

//        Map<String, Object> map = new HashMap<>();
//        map.put("state", 200);
//        map.put("msg", "登录成功！");
//        map.put("principal", authentication.getPrincipal());
//        response.setContentType("application/json;charset=utf-8");
//        PrintWriter out = response.getWriter();
//        // 对象转json传输给前端
//        out.write(new ObjectMapper().writeValueAsString(map));
//        out.flush();
//        out.close();
    }
}
